<template>
  <div class="app-container">
    <div>
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
          :filter-btn="filterInfo.btn"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-del>
            <el-button :disabled="!canDelete" @click="del()">删除</el-button>
          </template>
        </NewPageFilter>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
      />
    </div>
    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
      @reset="handleClose"
    >
      <el-form
        :model="formData"
        ref="form"
        :rules="rules"
        label-width="120px"
        class="paddingBox formBox flex_wrap_start_start"
      >
        <el-row>
          <el-col
            v-for="(item, index) in dialogInfo.fieldList"
            :span="item.span || 12"
            :gutter="20"
          >
            <el-form-item
              :label="item.label"
              :prop="item.value"
              style="width: 100%"
              class="formItem"
            >
              <el-input
                v-if="
                  !item.type ||
                  item.type === 'input' ||
                  item.type === 'textarea'
                "
                v-model="formData[item.value]"
                :type="item.type"
                :maxlength="item.maxlength || 500"
                :autosize="{
                  minRows: 1,
                }"
                style="width: 100%"
              />
              <SelectModel
                v-if="item.type === 'selectModel'"
                v-model.trim="formData[item.value]"
                typeCode="flow_module"
              />
              <el-button v-if="item.type === 'button'" @click="showUseDialog"
                >点击查看</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </PageDialog>
    <PageDialog
      v-show="dialogUseInfo.visible"
      :title="dialogUseInfo.title"
      v-model:visible="dialogUseInfo.visible"
      :width="dialogUseInfo.width"
      :bt-loading="dialogUseInfo.btLoading"
      :bt-list="dialogUseInfo.btList"
    >
      <div class="rowTitle">可用系统内置变量</div>
      <div class="infoBox">
        <div v-for="(item, index) in useInstructionsData" :key="index">
          <span class="title">
            {{ '(' + (index + 1) + ')' }}{{ item.label }}:
          </span>
          <span class="info">{{ item.info }}</span>
        </div>
      </div>
      <div class="rowTitle">可用对象变量</div>
      <div class="infoBox">
        <el-table :data="tableData" max-height="200px" style="width: 100%">
          <el-table-column prop="code" label="字段名" />
          <el-table-column prop="name" label="描述" />
        </el-table>
      </div>
      <div class="rowTitle">变量格式化</div>
      <div class="infoBox">
        <div v-for="(item, index) in valueBox" :key="index">
          <span class="title">{{ '(' + (index + 1) + ')' }}</span>
          <span class="info">{{ item.info }}</span>
        </div>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="scheduleTaskType">
import {
  getScheduleTaskTypePage,
  delScheduleTaskType,
  postScheduleTaskType,
  putScheduleTaskType,
  getScheduleTaskTypeField,
  getScheduleTaskTypeById,
  enableScheduleTaskType,
  disableScheduleTaskType,
} from '@/api/core'
const { proxy } = getCurrentInstance()
// 过滤相关配置
const filterInfo = ref({
  query: {},
  copyQuery: {},
  list: [
    {
      componentType: 'input',
      label: '任务分类名称',
      value: 'nameLike',
      event: search,
    },
    {
      componentType: 'input',
      label: '任务编码',
      value: 'codeLike',
      event: search,
    },
    {
      componentType: 'select-model',
      label: '所属模块',
      value: 'sourceModule',
      event: search,
      code: 'flow_module',
    },
    {
      componentType: 'input',
      label: '任务标题',
      value: 'titleLike',
      event: search,
    },
    {
      componentType: 'input',
      label: '任务描述',
      value: 'subTitleLike',
      event: search,
    },
    {
      componentType: 'select-model',
      label: '状态',
      value: 'status',
      event: search,
      code: 'new_enabled_type',
    },
  ],
  btn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('scheduleTaskType:add'),
    },
    {
      type: 'slot',
      value: 'del',
      show: proxy.$permission('scheduleTaskType:del'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: getScheduleTaskTypePage,
  data: [],
  selections: [],
  fieldList: [
    { label: '任务分类名称', value: 'name' },
    { label: '任务编码', value: 'code' },
    { label: '所属模块', value: 'sourceModuleValue' },
    { label: '任务标题', value: 'title' },
    { label: '任务描述', value: 'subTitle' },
    { label: '业务对象', value: 'viewName' },
    { label: '状态', value: 'statusValue' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('scheduleTaskType:update'),
        ifRender: function (row) {
          return row.status === 0
        },
      },
      {
        label: '启用',
        event: openTask,
        show: proxy.$permission('scheduleTaskType:open'),
        ifRender: function (row) {
          return row.status === 0
        },
      },
      {
        label: '停用',
        event: stopTask,
        show: proxy.$permission('scheduleTaskType:stop'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        event: del,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('scheduleTaskType:del'),
      },
    ],
  },
})
const dialogInfo = ref({
  visible: false,
  title: '新增日程任务分类',
  btLoading: false,
  width: '720px',
  fieldList: [
    {
      label: '任务分类名称',
      value: 'name',
    },
    {
      label: '任务编码',
      value: 'code',
    },
    {
      label: '所属模块',
      value: 'sourceModule',
      type: 'selectModel',
    },
    {
      label: '业务对象',
      value: 'viewName',
    },
    {
      label: 'PC处理URL地址',
      value: 'url',
    },
    {
      label: 'PC详情URL地址',
      value: 'detailUrl',
    },
    {
      label: 'APP处理URL地址',
      value: 'appUrl',
    },
    {
      label: 'APP详情URL地址',
      value: 'appDetailUrl',
    },
    {
      label: '任务标题',
      value: 'title',
      span: 24,
    },
    {
      label: '任务描述',
      value: 'subTitle',
      span: 24,
      type: 'textarea',
    },
    {
      label: '变量使用说明',
      type: 'button',
    },
  ],
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '提交',
      type: 'primary',
      event: submitConfirm,
      show: true,
    },
  ],
})
const dialogUseInfo = ref({
  visible: false,
  title: '变量使用说明',
  btLoading: false,
  width: '720px',
  btList: [{ label: '关闭', event: handleUseClose, show: true }],
})
const useInstructionsData = ref([
  {
    label: 'deptName[创建用户所在部门名称]',
    info: '${deptName}',
  },
  {
    label: 'name[任务分类名称]',
    info: '${name}',
  },
])
const valueBox = ref([
  {
    info: '字典项id转换为字典项名称，比如 ${sexId@sex},把性别id转换为对应的性别名称',
  },
  {
    info: '日期格式化，比如${createTime@YYYY-MM-dd}，把时间格式化为年-月-日。支持所有的Java日期格式',
  },
  {
    info: '数字的格式化，比如 ${amount@#.00}，格式化为 2位小数。支持Java数字化格式',
  },
])
const formData = ref({})
const rules = ref({
  name: [{ required: true, trigger: 'blur', message: '请输入任务分类名称' }],
  code: [
    {
      required: true,
      trigger: 'blur',
      validator: validateLetterNum,
    },
  ],
  sourceModule: [
    { required: true, trigger: 'change', message: '请选择所属模块' },
  ],
})
const tableData = ref([])

const canDelete = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
})

function validateLetterNum(rule, value, callback) {
  if (value === '' || value === undefined) {
    callback(new Error('请输入编码'))
  } else {
    // 最多输入200个字符，并且以小写字母开头
    let reg = /^[a-z]{1}([A-Za-z0-9]{0,200})$/
    if (!reg.test(value)) {
      callback(new Error('编码只能由英文字母、数字组成，且必须以小写字母开头'))
      return
    }
    callback()
  }
}
//创建
function create() {
  dialogInfo.value.visible = true
}
function update(row = undefined) {
  getScheduleTaskTypeById(row.id).then((res) => {
    if (res && res.success) {
      formData.value = res.data
      dialogInfo.value.visible = true
    }
  })
}
function handleClose() {
  proxy.$refs['form'].resetFields()
  dialogInfo.value.visible = false
  formData.value = {}
}
function submitConfirm() {
  proxy.$refs['form'].validate((valid) => {
    if (valid) {
      const api = formData.value.id ? putScheduleTaskType : postScheduleTaskType
      api(formData.value).then((res) => {
        if (res && res.success) {
          handleClose()
          getList()
        }
      })
    } else {
      proxy.$message.warning('请按照提示输入正确数据')
    }
  })
}
function showUseDialog() {
  tableData.value = []
  if (formData.value.viewName) {
    getScheduleTaskTypeField({
      viewName: formData.value.viewName,
    }).then((res) => {
      if (res && res.success) {
        for (let k in res.data) {
          tableData.value.push({
            code: k,
            name: res.data[k],
          })
        }
        dialogUseInfo.value.visible = true
      }
    })
  } else {
    dialogUseInfo.value.visible = true
  }
}
function handleUseClose() {
  dialogUseInfo.value.visible = false
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery)
  search()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function openTask(row = undefined) {
  enableScheduleTaskType([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function stopTask(row = undefined) {
  disableScheduleTaskType([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//删除
function del(row = undefined) {
  const ids = _getIds(row)
  delScheduleTaskType(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.value.selections.length > 0) {
      ids = tableInfo.value.selections.map((row) => row.id)
    }
  }
  return ids
}
</script>

<style lang="scss" scoped>
.rowTitle {
  font-size: 16px;
  font-weight: 700;
  margin: 10px 0;
}
.infoBox {
  padding-left: 16px;
  .title {
    font-weight: 700;
  }
}
.formItem.is-error {
  margin-bottom: 24px !important;
}
</style>
